package net.crowdloud.client.groups;

import java.util.List;

import net.crowdloud.client.GlobalVariables;
import net.crowdloud.client.user.UsersListPage;
import net.crowdloud.shared.engine.CrowdLoudGroupsEngine;
import net.crowdloud.shared.entities.Groups;
import net.crowdloud.shared.entities.User;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * 
 * @UserManual
 */
public class GroupsList extends VerticalPanel {

	public GroupsList(String[] groups) {

		this.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

		if (groups != null) {

			for (int i = 0; i < groups.length; i++) {

				HorizontalPanel hp = new HorizontalPanel();
				hp.setSpacing(30);

				for (int j = 0; j < 6; j++) {

					if (i == groups.length) {

						hp.add(groupLink(Groups.GROUP_NONE));

						break;

					} else {

						String group = groups[i];

						hp.add(groupLink(group));

						i++;
					}
				}

				this.add(hp);
			}
		}
	}

	private Anchor groupLink(final String group) {

		Anchor groupName = new Anchor(group);
		groupName.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				List<User> usersGroup = CrowdLoudGroupsEngine.getUsersGroup(
						GlobalVariables.users, group);

				RootPanel.get().clear();
				RootPanel.get().add(new UsersListPage(usersGroup, group));
			}
		});

		return groupName;
	}

}
